/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.enba.boot.swagger.config;

import com.enba.boot.swagger.properties.Kinfe4jProperties;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import io.swagger.annotations.Api;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@EnableOpenApi
@EnableConfigurationProperties(Kinfe4jProperties.class)
@Configuration
@Import(BeanValidatorPluginsConfiguration.class)
public class Knife4jConfig {

  private final OpenApiExtensionResolver openApiExtensionResolver;

  private final Kinfe4jProperties kinfe4jProperties;

  public Knife4jConfig(
      OpenApiExtensionResolver openApiExtensionResolver, Kinfe4jProperties kinfe4jProperties) {
    this.openApiExtensionResolver = openApiExtensionResolver;
    this.kinfe4jProperties = kinfe4jProperties;
  }

  @Bean(value = "api")
  public Docket api() {
    return new Docket(DocumentationType.OAS_30)
        .apiInfo(apiInfo())
        .groupName(kinfe4jProperties.getGroupName())
        .select()
        // 这里指定Controller扫描包路径
        // .apis(RequestHandlerSelectors.basePackage("com.example.testknife4j6.controller"))
        .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
        .paths(PathSelectors.any())
        .build()
        .extensions(openApiExtensionResolver.buildExtensions(kinfe4jProperties.getGroupName()));
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title(kinfe4jProperties.getTitle())
        .description(kinfe4jProperties.getDescription())
        .termsOfServiceUrl("url to the terms of service")
        .contact(
            new Contact(
                kinfe4jProperties.getContactName(),
                kinfe4jProperties.getContactUrl(),
                kinfe4jProperties.getContactEmail()))
        .version(kinfe4jProperties.getVersion())
        .build();
  }
}
